const socket = io('/')
const videoGrid = document.getElementById('video-grid')
const myPeer = new Peer(undefined, {
  host: '/',
  port: '3002',

})
// function pro() { return new Promise((resolve,reject)=>{var uname= window.prompt("输入一个用户名",""); resolve(uname)});}
// pro().then((uname)=>{
// socket.emit('join-room', ROOM_ID, uname )
const myVideo = document.createElement('video')
myVideo.muted = true
const peers = {}
navigator.mediaDevices.getDisplayMedia({
  video: {
    cursor: "always"
  },
  audio: true
}).then(stream => {
  addVideoStream(myVideo, stream)
  myPeer.on('call', call => {
    call.answer(stream)
    
    call.on('stream', userVideoStream => {
      const video = document.createElement('video')
      addVideoStream(video, userVideoStream)
    })
  })

  socket.on('user-connected', userId => {
    connectToNewUser(userId, stream)
  })
})
// socket.on('stream',(u,s)=>{
//   var video = document.createElement('video')
//   video.title=u+'的画面'
//   var videoUrl=window.URL.createObjectURL(s.data);// blob.data gives actual data
//   video.src = videoUrl;
// })
socket.on('user-disconnected', userId => {
  if (peers[userId]) peers[userId].close()
})

myPeer.on('open', id => {
  socket.emit('join-room', ROOM_ID, id)
})

function connectToNewUser(userId, stream) {

  // socket.emit('stream',userId,stream)
  const call = myPeer.call(userId, stream)
  const video = document.createElement('video')
  call.on('stream', userVideoStream => {
    addVideoStream(video, userVideoStream)
  })
  call.on('close', () => {
    video.remove()
  })

  peers[userId] = call
}

function addVideoStream(video, stream) {
  video.srcObject = stream
  video.addEventListener('loadedmetadata', () => {
    video.play()
  })
  videoGrid.append(video)
}

// }
// )